package com.cmhi.softmbh.util;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.StatFs;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Pattern;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * @author 陈华
 */
public class DeviceUtils {
    /**
     * CPU芯片型号信息或者芯片组型号信息
     */
    public static String getCpuInfo() {
        try {
            String str = "";
            String[] arrayOfString;
            StringBuilder cpuModel = new StringBuilder();
            FileReader fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr, 8192);
            String readLine;
            while ((readLine = br.readLine()) != null) {
                if (readLine.startsWith("Hardware")) {
                    str = readLine;
                }
            }
            arrayOfString = str.split("\\s+");
            if (arrayOfString.length > 0) {
                for (int i = 2; i < arrayOfString.length; i++) {
                    cpuModel.append(arrayOfString[i]).append(" ");
                }
            }
            br.close();
            return cpuModel.toString().trim();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
    static class CpuFilter implements FileFilter {
        @Override
        public boolean accept(File pathname) {
            // Check if filename is "cpu", followed by a single digit number
            if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                return true;
            }
            return false;
        }
    }
    /**
     * CPU芯片核心数量
     */
    public static int getCpuCoresCount() {
        // Private Class to display only CPU devices in the directory listing
        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            // Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            // Default to return 1 core
            return 1;
        }
    }
    /**
     * 获取android总运行内存大小
     */
    public static long getRamSize() {
        // 系统内存信息文件
        String str1 = "/proc/meminfo";
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            // 读取meminfo第一行，系统总内存大小
            str2 = localBufferedReader.readLine();
            arrayOfString = str2.split("\\s+");
//            for (String num : arrayOfString) {
//                AppUtils.Log("内存 子项", num + "\t");
//            }
            // 获得系统总内存，单位是KB
            long i = Long.parseLong(arrayOfString[1]);
            //int值乘以1024转换为long类型
            initial_memory =  i / 1024;
//            long mode=initial_memory%500;
//            if(mode>250){
//                initial_memory+=500-mode;
//            }else{
//                initial_memory-=mode;
//            }
            localBufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        AppUtils.debugLog("内存总大小---" + initial_memory + "");
        return initial_memory ;// Byte转换为KB或者MB，内存大小规格化
    }
    /**
     * 获得内部存储总大小
     *
     * @return String
     */
    public static String getRomSize() {
        StatFs stat = new StatFs("/data");
        long blockSize = stat.getBlockSizeLong();
        long totalBlocks = stat.getBlockCountLong();
        return (blockSize * totalBlocks) / 1024L / 1024L + "";

    }
    /**
     * 获得内部存贮剩余容量，即可用大小
     *
     * @return String
     */
    public static long getStorageSize() {
        StatFs stat = new StatFs("/data");
        long blockSize = stat.getBlockSizeLong();
        long availableBlocks = stat.getAvailableBlocksLong();
        return (blockSize * availableBlocks) / 1024L / 1024L;
    }
    /**
     * 获取屏幕分辨率
     *
     * @return String
     */
    public static String getScreenRes(Context context) {
        WindowManager wm = (WindowManager) (context.getSystemService(Context.WINDOW_SERVICE));
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels + "x" + dm.heightPixels;
    }
    /**
     * CPU最大运行频率
     */
    public static int getMaxCpuFreq() {
        int result = 0;
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
            br = new BufferedReader(fr);
            String text = br.readLine();
            if (text != null) {
                result = Integer.parseInt(text.trim());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 获取屏幕密度
     *
     * @param context
     * @return
     */
    public static float getScreenDensity(Context context) {
        return context.getResources().getDisplayMetrics().densityDpi;
    }
    public interface GpuInfo{
        /**
         *
         * @param gpuSupplier gpu供应商
         * @param gpuRender gpu 渲染器
         * @param gpuVersion gpu 版本
         */
        public void onGpuInfo(String gpuSupplier,String gpuRender,String gpuVersion);
    }

    public static void getGpuInfo(GLSurfaceView glSurfaceView,GpuInfo info){
        glSurfaceView.setEGLContextClientVersion(2);
        glSurfaceView.setRenderer(new GLSurfaceView.Renderer() {
            @Override
            public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
              String gpuSupplier=  gl10.glGetString(GL10.GL_VENDOR);
              String gpuRender= gl10.glGetString(GL10.GL_RENDERER);
              String gpuVersion=gl10.glGetString(GL10.GL_VERSION);
              if (info!=null){
                  info.onGpuInfo(gpuSupplier,gpuRender,gpuVersion);
              }
            }

            @Override
            public void onSurfaceChanged(GL10 gl10, int i, int i1) {

            }

            @Override
            public void onDrawFrame(GL10 gl10) {

            }
        });
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

    }
}
